package com.rndemo.entity;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by tangzejin on 2017/1/15.
 * 功能说明：map的tostring 改为json的
 *
 */

public class MapJson<K,V> extends HashMap{
    @Override
    public String toString() {
        if (isEmpty()) {
            return "{}";
        }

        StringBuilder buffer = new StringBuilder(size() * 28);
        buffer.append('{');
        Iterator<Entry<K, V>> it = entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<K, V> entry = it.next();
            Object key = entry.getKey();
//            if (key == null){
//                return entry.getValue().toString();
//            }else
            if (key != this) {
                buffer.append("\"");
                buffer.append(key);
                buffer.append("\"");
            } else {
                buffer.append("(this Map)");
            }
            buffer.append(':');
            Object value = entry.getValue();
            if (value != this) {
                if (value.getClass() == String.class){
                    buffer.append("\"");
                    buffer.append(value);
                    buffer.append("\"");
                }else{
                    buffer.append(value);
                }
            } else {
                buffer.append("(this Map)");
            }
            if (it.hasNext()) {
                buffer.append(", ");
            }
        }
        buffer.append('}');
        return buffer.toString();
    }
}
